let table;
$(function () {
    initPage();
    initTable();
})

function initPage() {
    let item = localStorage.getItem("admin");
    let admin = JSON.parse(item);
    $("#userName").html(admin.adminName);
}

function initTable() {
    table = $('#dataTable').DataTable({
        serverSide: true,
        sort: false,
        // sUrl: body_data,
        ajax: {
            "type": "POST",
            "url": "/admin/list_users",
            "data": function (e) {
                showProgress();
                return $.extend({}, e, {});
            },
            "error": function () {
                layer.msg("您的网络出现了一点问题", {
                    icon: 2
                });
            },
            "dataSrc": function (res) {
                layer.closeAll('loading');
                if (res.code == 401) {
                    console.log("没有权限");
                    layer.alert(res.message, {
                        skin: 'layui-layer-molv' //样式类名
                        , closeBtn: 0
                    }, function () {
                        location.href = "/login.html";
                    });
                    return null;
                }
                return res.data;
            },
            "complete": function () {
                layer.closeAll('loading');
            }
        },
        fnServerParams: function (aoData) {
            let words = $.trim($("input[type='search']").val());
            if (words.length != 0) {
                aoData.anyWords = words;
            }
        },
        // fnServerData:function(response){
        //     console.log(response);
        // },
        // aoColumns:[{
        //     "classNo":$("#gradeNoSelect").val()
        // }],
        pageLength: 25,　//初始化显示几条数据
        fixedHeader: true,　//这个是用来固定头部
        fixedColumns: { //这个是用来固定列的
            leftColumns: 0,
            rightColumns: 1
        },
        fnInitComplete: function (oSettings, json) {
            if (oSettings.jqXHR == null) {
                layer.alert("您的登录已经过期，请重新登录", {
                    skin: 'layui-layer-molv' //样式类名
                    , closeBtn: 0
                }, function () {
                    location.href = "/login.html";
                });
            }
        },
        language: {　　// 这是修改语言的显示
            buttons: {
                pageLength: {
                    _: "显示%d条",
                    '-1': "全部显示"
                }
            },
            sEmptyTable: "没有找到您要查询的内容",
            sLoadingRecords: "载入中...",
            sInfo: "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
            sLengthMenu: "显示 _MENU_ 项结果",
            paginate: {
                first: "首条",
                previous: "前一页",
                next: "下一页",
                last: "末页"
            },
            "info": "第_PAGE_页/共_PAGES_页",
            "infoEmpty": "未找到相关数据",
            "search": "搜索",
            "zeroRecords": "未找到相关数据",
            "decimal": ".",
            "thousands": ",",
            // "bProcessing": true, //没有排序功能 所以这边不需要
            // "sProcessing": "<img src='" + webroot + "/static/image/loading.gif' /> 数据加载中...",//加载动画功能 自己实现了   所以这边也不需要
        },

        // data: body_data,　//data　这个参数就是用来传入数据的　　body_data 就是json数据,这个还有ajax的方法
        columns: [　//这个是显示到界面上的个数据　格式为 {data:'显示的字段名'}
            {data: 'account', "className": "text-center"},
            {data: 'name', "className": "text-center"},
            {data: 'organization', "className": "text-center"},
            {data: 'position', "className": "text-center"},
            {data: 'email', "className": "text-center"},
            {data: 'phone', "className": "text-center"},
            {data: 'receiptTitle', "className": "text-center"},
            {data: 'taxNumber', "className": "text-center", "width": "%10"},
            {data: 'receiptType', "className": "text-center", "width": "%10"},
            {
                data: 'date', "className": "text-center", render: function (data, type, row, meta) {
                    if (row.date == null) {
                        return "";
                    }
                    return commonClass.dateTimeString(row.date);
                }
            },
            {
                // sWidth: "15%",
                data: 'account', //每一个数据都是可以用来修改传入的参数　
                className: "text-center",
                render: function (data, type, row, meta) {　//
                    let h = "<div class='col-md-12'>";
                    let deleteA = "<a href='javascript:;' title='删除' data-id='" + data + "' onclick='deleteUser(this)' style='color: red'><span class='glyphicon glyphicon-trash col-md-4'></span></a>";
                    let editA = "<a href='javascript:;' title='编辑' data-row='" + JSON.stringify(row) + "' onclick='showEditModal(this)' ><span class='glyphicon glyphicon-pencil col-md-4'></span></a>";
                    let initPass = "<a href='javascript:;' title='初始化密码' data-id='" + row.account + "' onclick='initPassWord(this)' ><span class='glyphicon glyphicon-lock col-md-4'></span></a>";
                    h += deleteA;
                    h += editA;
                    h += initPass;
                    h += "</div>";
                    return h;
                }
            }
        ]
    });
}

function initPassWord(curr) {
    let id = $(curr).data("id");
    layer.confirm('此用户的密码将会被初始化为用户的账号，您确定要执行此操作？', {
        btn: ['确认', '取消'] //按钮
    }, function () {
        $.ajax({
            url: "/admin/init_password",
            data: {
                userId: id
            },
            type: "get",
            success: function (response) {
                if (response.code == 200) {
                    layer.msg('操作成功', {icon: 1});
                } else if (response.code == 401) {
                    layer.alert(response.message, {
                        skin: 'layui-layer-molv' //样式类名
                        , closeBtn: 0
                    }, function () {
                        location.href = "/login.html";
                    });
                } else {
                    layer.msg(response.message, {
                        icon: 2
                    });
                }
            },

            error: function () {
                layer.msg("您的网络可能出了点问题", {
                    icon: 2
                })
            },
            beforeSend: function () {
                showProgress();
            },
            complete: function () {
                layer.closeAll('loading');
            }
        })

    }, function () {

    });
}

function deleteUser(curr) {
    let account = $(curr).data("id");
    layer.confirm('删除后无法恢复，您确定要删除此用户？', {
        btn: ['确认', '取消'] //按钮
    }, function () {
        $.ajax({
            url: "/admin/delete/" + account,
            type: "delete",
            success: function (response) {
                if (response.code == 200) {
                    table.draw(false);
                    layer.msg('删除成功', {icon: 1});
                } else if (response.code == 401) {
                    layer.alert(response.message, {
                        skin: 'layui-layer-molv' //样式类名
                        , closeBtn: 0
                    }, function () {
                        location.href = "/login.html";
                    });
                } else {
                    layer.msg(response.message, {
                        icon: 2
                    });
                }
            },

            error: function () {
                layer.msg("您的网络可能出了点问题", {
                    icon: 2
                })
            },
            beforeSend: function () {
                showProgress();
            },
            complete: function () {
                layer.closeAll('loading');
            }
        })

    }, function () {

    });

}

function showProgress() {
    layer.load(0, {
        shade: [0.5, '#fff'] //0.1透明度的白色背景
    });
}

function showEditModal(curr) {
    let row = $(curr).data("row");
    console.log(row.account);
    $("#userId").val(row.account);
    $("#name").val(row.name);
    $("#organization").val(row.organization);
    $("#position").val(row.position);
    $("#phone").val(row.phone);
    $("#email").val(row.email);
    $("#taxNum").val(row.taxNumber);
    $("#receiptTitle").val(row.receiptTitle);
    $("#receiptType").val(row.receiptType);
    $("#editModal").modal('show');
}

function commit() {
    let account = $("#userId").val();
    let name = $("#name").val();
    let organization = $("#organization").val();
    let position = $("#position").val();
    let phone = $("#phone").val();
    let email = $("#email").val();
    let taxNum = $("#taxNum").val();
    let receiptTitle = $("#receiptTitle").val();
    let receiptType = $("#receiptType").val();


    if ($.trim(name).length == 0) {
        scrollToDiv("#name");
        layer.msg("用户名不能为空", {
            icon: 2
        });
        return;
    }

    if ($.trim(organization).length == 0) {
        scrollToDiv("#organization");
        layer.msg("所属部门不能为空", {
            icon: 2
        });
        return;
    }
    if ($.trim(position).length == 0) {
        layer.msg("用户职位不能为空", {
            icon: 2
        });
        return;
    }

    if ($.trim(phone).length != 0 && commonClass.validMobile(phone)) {
        layer.msg("用户手机号不能为空", {
            icon: 2
        });
        return;
    }
    if ($.trim(email).length == 0) {
        layer.msg("用户邮箱不能为空", {
            icon: 2
        });
        return;
    }
    if (!commonClass.validEmail(email)) {
        layer.msg("用户email格式不正确", {
            icon: 2
        });
        return;
    }
    if($.trim(receiptTitle).length != 0){

        if ($.trim(taxNum).length == 0){
            layer.tips('如果填了用户收据抬头，则税号为必填项', '#taxNum', {
                tips: [1, '#ff0000'],
                time: 4000
            });
            return;
        }

        if(receiptType.length == 0){
            layer.tips('如果填了用户收据抬头，则发票类型为必填项', '#receiptType', {
                tips: [1, '#ff0000'],
                time: 4000
            });
            return;
        }

    }

    let data = JSON.stringify({
        "account": account,
        "receiptTitle": receiptTitle,
        "phone": phone,
        "name": name,
        "organization": organization,
        "position": position,
        "email": email,
        "taxNumber": taxNum,
        "receiptType": receiptType
    });

    $.ajax({
        url: "/update",
        type: "post",
        contentType: "application/json",
        data: data,
        success: function (response) {
            if (response.code == 200) {
                layer.msg("更新成功", {
                    icon: 1
                });
                table.draw(false);
                $("#editModal").modal("hide");
            } else if (response.code == 401) {
                layer.alert(response.message, {
                    skin: 'layui-layer-molv' //样式类名
                    , closeBtn: 0
                }, function () {
                    location.href = "/login.html";
                });
            } else {
                layer.msg(response.message);
            }
        },
        complete: function () {
            layer.closeAll('loading');
        },
        error: function () {
            layer.msg("您的网络可能出现了一点问题!", {
                icon: 2
            });
        },
        beforeSend: function () {
            showProgress();
        }
    });
}

function scrollToDiv(dom) {
    $('html, body').animate({
        scrollTop: $(dom).offset().top - 200
    }, 500);
}